﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Diagnostics;
using Microsoft.Extensions.FileSystemGlobbing.Internal.PathSegments;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace 综合同步.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class ChartController : ControllerBase
    {
        static double s_dateTimeDiff = 0;
        private readonly ILogger<ChartController> _logger;

        public ChartController(ILogger<ChartController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IDictionary<string,object> GetArcData(string file)
        {
            DateTime date;
            string filetime = Path.GetFileNameWithoutExtension(file);
            string filepath = LocalServer.GetConfigValue<string>("DataPath")+file.Replace("StaticFiles/","").Replace("/","\\");
            Int64 VideoSpan = RedisClientBll.GetFileTimeSpan(filepath);
            try{
                date = DateTime.ParseExact(filetime.Substring(0,14),"yyyyMMddHHmmss",CultureInfo.CurrentCulture);
                s_dateTimeDiff = (date - new FileInfo(file).CreationTime).TotalSeconds;
            }catch(Exception){
                date = new FileInfo(file).CreationTime.AddSeconds(s_dateTimeDiff);
            }
            WRDataBase[] db = WRDataBase.CreateReadDB().ToArray();
            Dictionary<string,object> obj = new Dictionary<string,object>();
            obj.Add("data",db.SelectMany(o=>o.ArcingEntities.ToArray()).
                Where(o=>o.OccurTime>=date&&o.OccurTime<date.AddSeconds(VideoSpan)).
                Select(o=>new {
                    Index = (o.OccurTime-date).TotalSeconds,
                    ArcSpan = o.Span,
                    o.Strength,
                }).ToList());
            obj.Add("videoSpan",VideoSpan);
            return obj;
        }
    }
}
